package com.atom.wifiupload;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.atom.wifiupload.nanohttpd.ServerRunner;
import com.atom.wifiupload.utils.NetworkUtils;
import com.atom.wifiupload.utils.ServerDefaults;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * ============================================================
 * project: WIFI-Upload
 * package: com.atom.wifiupload
 * fileDescribe:
 * user: admin
 * email: 1299854942@qq.com
 * createTime: 2017/6/24  12:34
 * modify:
 * version:: V1.0
 * ============================================================
 **/
public class ServerLinkFragment extends Fragment {

    @BindView(R.id.iv_pc_and_phone)
    ImageView mIvPcAndPhone;
    @BindView(R.id.tv_content)
    TextView mTvContent;
    @BindView(R.id.mTvWifiIp)
    TextView mTvWifiIp;
    @BindView(R.id.tvRetry)
    TextView mTvRetry;
    @BindView(R.id.mTvWifiName)
    TextView mTvWifiName;

    private Unbinder mUnbinder;
    private Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wifi_server, null);
        mUnbinder = ButterKnife.bind(this, view);
        String wifiname = NetworkUtils.getConnectWifiSsid(mContext);
        if (!TextUtils.isEmpty(wifiname)) {
            mTvWifiName.setText(wifiname.replace("\"", ""));
        } else {
            mTvWifiName.setText("Unknow");
        }

        String wifiIp = NetworkUtils.getConnectWifiIp(mContext);
        if (!TextUtils.isEmpty(wifiIp)) {
            mTvRetry.setVisibility(View.GONE);
            mTvWifiIp.setText("http://" + NetworkUtils.getConnectWifiIp(mContext) + ":" + ServerDefaults.getPort());
            // 启动wifi传书服务器
            ServerRunner.startServer();
        } else {
            mTvWifiIp.setText("请开启Wifi并重试");
            mTvRetry.setVisibility(View.VISIBLE);
        }
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }
}
